package com.eam.eventhandler;

import com.eam.data.EamFacilitiesRepair;
import org.hibernate.Query;
import org.openbravo.base.exception.OBException;
import org.openbravo.base.model.Entity;
import org.openbravo.base.model.ModelProvider;
import org.openbravo.client.kernel.event.EntityDeleteEvent;
import org.openbravo.client.kernel.event.EntityNewEvent;
import org.openbravo.client.kernel.event.EntityPersistenceEventObserver;
import org.openbravo.client.kernel.event.EntityUpdateEvent;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.ConnectionProvider;
import org.openbravo.database.SessionInfo;
import org.openbravo.erpCommon.utility.Utility;
import org.openbravo.service.db.DalConnectionProvider;
import javax.enterprise.event.Observes;

public class FacilityRepairEventHandler extends EntityPersistenceEventObserver {
	private static Entity[] entities = { ModelProvider.getInstance().getEntity(EamFacilitiesRepair.ENTITY_NAME) };

	@Override
	protected Entity[] getObservedEntities() {
		return entities;
	}

	public void onUpdate(@Observes EntityUpdateEvent event) throws Throwable {
		if (!isValidEvent(event)) {
			return;
		}

	}

	public void onSave(@Observes EntityNewEvent event) {
		if (!isValidEvent(event)) {
			return;
		}

		String tabId = SessionInfo.getProcessId();

		if (tabId == null) {
			return;
		}

		// 获取项目
		EamFacilitiesRepair details = (EamFacilitiesRepair) event.getTargetInstance();
		
		EamFacilitiesRepair old_item = null;
		
		// 获取维保项目ID
		String m_id = details.getEamRepairItem().getId();
		//获取设备ID
		String groupId = details.getEamModelGroup().getId();

		String hql = "select efm from " + EamFacilitiesRepair.ENTITY_NAME + " efm where efm.emesRepairItem.id =:m_id and efm.eamModelGroup.id =:groupId ";
		Query query = OBDal.getInstance().getSession().createQuery(hql);
		query.setString("m_id", m_id);
		query.setString("groupId", groupId);
		old_item = (EamFacilitiesRepair) query.uniqueResult();
		
		if(old_item != null){
			String language = OBContext.getOBContext().getLanguage().getLanguage();
			ConnectionProvider conn = new DalConnectionProvider(false);
			throw new OBException(Utility.messageBD(conn, details.getEamRepairItem().getName()+"已经存在，请仔细检查。", language));
		}

		OBDal.getInstance().commitAndClose();
	}

	public void onDelete(@Observes EntityDeleteEvent event) {
		if (!isValidEvent(event)) {
			return;
		}
	}

}
